// pages/bill-pay/bill-pay.js

const requestToGetWxPayData = require('../../utils/request.js').requestToGetWxPayData
const requestToGetBillDetail = require('../../utils/request.js').requestToGetBillDetail
const toRecordDeatilPage = require('../../utils/wx-navigate.js').toRecordDeatilPage

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    bill_id: "",
    bill:{},

    showResult: false,
    result: { isSuccess: true, text: "交租成功", btnText1: '返回账本', }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let data = options.data ? JSON.parse(options.data) : {}
    this.setData({
      bill_id: data._id
    })
    console.log(data)
    this.toGetBillDetail()

  
  },

  toGetBillDetail(){
    requestToGetBillDetail(this.data.bill_id, res => {
      
      if (res.bill.trade_state === "SUCCESS" || res.bill.trade_state === "CLOSED") {
        wx.navigateBack({
          delta: 1
        })
        toRecordDeatilPage(res.bill)
      }else{
        this.setData({
          bill: res.bill
        })
      }

    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.toGetBillDetail()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  bingtap:function(){
    let bill_id = this.data.bill._id
    requestToGetWxPayData(bill_id,res => {
      console.log(res)
      let payData = res.payData

      wx.requestPayment({
        'timeStamp': payData.timeStamp,
        'nonceStr': payData.nonceStr ,
        'package': payData.package,
        'signType': payData.signType,
        'paySign': payData.paySign,
        'success': res=> {
          console.log('支付成功，跳转页面')
          app.updateIndexPageData()
          app.updateBookDetailPageData()
          this.setData({
            showResult: true
          })
          wx.setNavigationBarTitle({
            title: "交租成功"
          })
        },
        'fail': function (res) {
          console.log('支付失败')
        }
      })


    })
  },

  bindresultbtn1tap: function (e) {
    wx.navigateBack({
      delta: 1
    })
  },
})